<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\general\LihuaCity;
use app\common\model\general\LihuaSlide;
use app\common\model\general\LihuaStore;
use app\common\model\goods\LihuaGoods;
use app\common\model\goods\LihuaStock;
use app\common\model\LihuaComment;

/**
 * 首页分类门店评价
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city", type="string", required=true, description="城市名称或ID")
     * @ApiParams   (name="platform", type="string", required=false, description="平台")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1575716773","data":{"city_info":{"city_id":3,"city_name":"常州","am_time":["11:00","13:30"],"pm_time":["17:00","19:30"],"tel":"0519-88811711","min_price":0.01,"deliver_fee":0.01,"pay_types":["1","2","4"],"notice":"品质保证，绿色健康，吃的放心，欢迎订餐","enough":{"50":"10","100":"20"}},"slide_list":[{"title":"全力奋战，势必达成","pic":"https://lihua.czapi.cn/uploads/slide/2019/10/30525d9d7b9269b14.jpg","url":""},{"title":"母亲节","pic":"https://lihua.czapi.cn/uploads/slide/2019/10/39265d9d7d833cfdc.jpg","url":""}],"goods_list":[{"id":2341,"category_id":39,"name":"38元意式牛腩套餐","short_name":"牛腩","description":"意式牛腩+杏鲍菇腊肉+鱼香茄子+香油菠菜+红油鸭肫粒+玉米","pic":"http://image.lihua.com/images/newweb/2015/12/thumb_567e4db81f251.jpg","original_price":null,"price":38,"box_fee":1,"limit_num":0,"at_least":1,"is_alone_sale":1,"enable_stock":0},{"id":1070,"category_id":39,"name":"30元腊鸡块套餐","short_name":"腊鸡块","description":"腊鸡块+金针菇肉丝+莴笋鸡蛋+西兰花+椒盐花生","pic":"http://image.lihua.com/images/newweb/2015/11/thumb_564d781d37afb.JPG","original_price":null,"price":30,"box_fee":1,"limit_num":0,"at_least":1,"is_alone_sale":1,"enable_stock":0}]}})
     */
    public function index()
    {
        $city = $this->request->request('city', '');
        $plt  = strtolower($this->request->request('platform', 'app'));
        if (!$city || !in_array($plt, ['app','xcx'])) $this->error('参数错误');

        $city_info  = LihuaCity::getCityInfo($city);
        if (!$city_info) $this->error('当前城市暂未开放');
        if ($city_info['pay_types']) {
            $city_info['pay_types'] = $city_info['pay_types'][$plt];
        }

        $slide_list = LihuaSlide::getCitySlideList($city_info['city_id']);
        $goods_list = LihuaGoods::getCityGoodsList($city_info['city_id']);

        $this->success('OK', [
            'city_info'  => $city_info,
            'slide_list' => $slide_list,
            'goods_list' => $goods_list,
        ]);
    }

    /**
     * 分类
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID：3")
     * @ApiParams   (name="store_id", type="int", required=false, description="门店ID：18")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1567675144","data":{"category_list":[{"id":202,"name":"开心饮品（满35免送餐费）","goods":[{"id":50,"category_id":202,"name":"听装雪花啤酒","short_name":"雪花","description":"常温 净含量330ml（配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2018\/11\/thumb_5bdaa5ad5df8a.jpg","original_price":0,"price":5,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0}]},{"id":57,"name":"开心加料（单点不含餐具）","goods":[{"id":43,"category_id":57,"name":"蛋花汤料","short_name":"蛋花汤","description":"含汤碗 净含量8克（配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2016\/09\/thumb_57cfc743835e0.jpg","original_price":0,"price":2,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0},{"id":46,"category_id":57,"name":"雪菜汤料","short_name":"雪菜汤","description":"含汤碗 净含量3克（配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2016\/09\/thumb_57cfc709e088f.jpg","original_price":0,"price":1,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0},{"id":44,"category_id":57,"name":"三件套","short_name":"三件套","description":"三件套（不含汤勺，配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2018\/12\/thumb_5c0f521445dd8.JPG","original_price":0,"price":2.5,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0},{"id":45,"category_id":57,"name":"米饭","short_name":"白饭","description":"套餐里已含一份米饭（配餐产品，不单独售卖）（不配套餐具）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2016\/09\/thumb_57cfc71baf78d.jpg","original_price":0,"price":3,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0}]},{"id":218,"name":"暖心砂锅","goods":[{"id":32797,"category_id":218,"name":"特别的爱砂锅","short_name":"特爱砂锅","description":"六荤六素全家福","pic":"http:\/\/image.lihua.com\/images\/newweb\/2019\/08\/thumb_5d5b494cbe158.jpg","original_price":0,"price":25,"box_fee":2,"limit_num":1,"at_least":1,"is_alone_sale":1,"enable_stock":0}]}]}})
     */
    public function category()
    {
        $city_id  = (int)$this->request->request('city_id', 0);
        $store_id = (int)$this->request->request('store_id', 0);
        if (!$city_id) $this->error('参数错误');

        $list = LihuaGoods::getCityCategoryGoodsList($city_id, $store_id);
        $this->success('OK', ['category_list' => $list]);
    }

    /**
     * 城市列表
     *
     * @ApiMethod   (POST)
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1566239128","data":{"city_list":[{"id":1,"name":"北京"},{"id":2,"name":"上海"},{"id":3,"name":"常州"},{"id":4,"name":"南京"},{"id":5,"name":"苏州"},{"id":6,"name":"无锡"},{"id":7,"name":"广州"}]}})
     */
    public function city()
    {
        $list = LihuaCity::getCityList();
        $this->success('OK', ['city_list' => $list]);
    }

    /**
     * 门店及库存
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=false, description="城市id")
     * @ApiParams   (name="lng", type="string", required=true, description="经度：119.957481")
     * @ApiParams   (name="lat", type="string", required=true, description="纬度：31.713501")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1571296846","data":{"store":{"id":18,"name":"湖塘","city_id":3},"stocks":{"1180":5000,"2228":200}}})
     */
    public function store() {
        $city_id = $this->request->request('city_id', 0);
        $lng     = $this->request->request('lng', '');
        $lat     = $this->request->request('lat', '');
        if (!$city_id || !is_numeric($lng) || !is_numeric($lat)) $this->error('参数错误');

        $store = LihuaStore::getPointStore($city_id, $lng, $lat);
        $data['store']  = $store;
        $data['stocks'] = null;
        if ($store['id'] > 0) {
            $goods_ids  = LihuaGoods::where(['city_id' => $city_id, 'enable_stock' => 1])->column('id');
            if (!empty($goods_ids)) {
                $data['stocks'] = LihuaStock::whereIn('goods_id', $goods_ids)
                    ->where('store_id', $store['id'])
                    ->whereNotNull('num')
                    ->column('goods_id,num');
            }
        }
        $this->success('OK', $data);
    }

    /**
     * 默认门店
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市id")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1570282516","data":{"id":25,"name":"丽华"}})
     */
    public function defstore() {
        $city_id  = $this->request->request('city_id', 0);
        if (!$city_id) $this->error('参数错误');

        $row = LihuaStore::where(['city_id' => $city_id, 'isdef' => 1])->field('id,name')->find();
        if (!$row) {
            $row = ['id' => 0, 'name' => ''];
        }

        $this->success('OK', $row);
    }

    /**
     * 评价列表
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="page", type="int", required=true, description="当前页，默认第1页")
     * @ApiParams   (name="page_size", type="int", required=false, description="每页条数，默认20条")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1571327639","data":{"page":1,"total":2,"page_size":20,"total_page":1,"list":[{"id":2,"nickname":"大帝","score":4.3,"content":"酸菜鸡真的很酸爽，吃了还想吃，赞","pics":["https:\/\/lihua.czapi.cn\/uploads\/goods\/2019\/10\/48345da884e09488c.jpg"],"time":"2019-10-14 12:31"},{"id":1,"nickname":"灰太狼","score":5,"content":"滑鸡饭分量足，真的好好吃","pics":["https:\/\/lihua.czapi.cn\/uploads\/goods\/2019\/10\/20725d9efea561b3e.jpg","https:\/\/lihua.czapi.cn\/uploads\/goods\/2019\/10\/56775da8853c519a2.jpg"],"time":"2019-10-11 19:17"}]}})
     */
    public function comment()
    {
        $city_id   = (int)$this->request->post('city_id');
        if (!$city_id) $this->error('参数错误');
        $page      = max(1, (int)$this->request->post('page'));
        $page_size = (int)$this->request->post('page_size') ? : 20;
        $data      = [
            'page'       => $page,
            'total'      => 0,
            'page_size'  => $page_size,
            'total_page' => 0,
            'list'       => []
        ];

        $where = ['city_id' => $city_id, 'status' => 1];
        $total = LihuaComment::where($where)->count();
        if ($total) {
            $data['total']      = $total;
            $data['total_page'] = ceil($total/$page_size);
            $res = LihuaComment::where($where)
                ->field('id,nickname,content,goods_score,courier_score,service_score,pics,create_time')
                ->order('id', 'desc')->page($page, $page_size)->select();
            $list = [];
            foreach ($res as $k => $v) {
                $score  = round(($v['goods_score'] + $v['courier_score'] + $v['service_score']) / 3, 1);
                $list[] = [
                    'id' => $v['id'],
                    'nickname' => $v['nickname'],
                    'score'    => $score,
                    'content'  => htmlentities($v['content']),
                    'pics'     => explode(',', $v['pics']),
                    'time'     => date('Y-m-d H:i', $v['create_time']),
                ];
            }
            $data['list'] = $list;
        }

        $this->success('OK', $data);
    }

}
